
class WebRequestExtension {
  constructor() {
    // 初始化扩展
  }

  getInfo() {
    return {
      id: 'webRequest',
      name: '网页请求',
      color1: '#4a6cd4',
      color2: '#3a59a9',
      color3: '#2a4d8f',
      menuIconURI: '',
      blockIconURI: '',
      blocks: [
        {
          opcode: 'makeRequest',
          blockType: Scratch.BlockType.REPORTER,
          text: '向 [URL] 发起 [METHOD] 请求，数据 [DATA]',
          arguments: {
            URL: {
              type: Scratch.ArgumentType.STRING,
              defaultValue: 'https://httpbin.org/get'
            },
            METHOD: {
              type: Scratch.ArgumentType.STRING,
              menu: 'methodMenu'
            },
            DATA: {
              type: Scratch.ArgumentType.STRING,
              defaultValue: '{}'
            }
          },
          func: 'makeRequest'
        },
        {
          opcode: 'getLastResponse',
          blockType: Scratch.BlockType.REPORTER,
          text: '获取最后响应内容',
          arguments: {},
          func: 'getLastResponse'
        }
      ],
      menus: {
        methodMenu: {
          acceptReporters: true,
          items: [
            {text: 'GET', value: 'GET'},
            {text: 'POST', value: 'POST'},
            {text: 'PUT', value: 'PUT'},
            {text: 'DELETE', value: 'DELETE'},
            {text: 'PATCH', value: 'PATCH'}
          ]
        }
      }
    };
  }

  async makeRequest(args) {
    const url = args.URL;
    const method = args.METHOD;
    let data = args.DATA;

    try {
      // 准备请求选项
      const options = {
        method: method,
        headers: {
          'Content-Type': 'application/json'
        }
      };

      // 如果是POST、PUT、PATCH等方法，添加请求体
      if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
        try {
          // 尝试解析数据为JSON
          const parsedData = JSON.parse(data);
          options.body = JSON.stringify(parsedData);
        } catch (e) {
          // 如果数据不是有效的JSON，直接使用字符串
          options.body = data;
        }
      }

      // 发起请求
      const response = await fetch(url, options);
      const responseBody = await response.text();

      // 尝试解析响应为JSON
      try {
        this.lastResponse = JSON.parse(responseBody);
      } catch (e) {
        // 如果响应不是JSON格式，返回原始文本
        this.lastResponse = {
          status: response.status,
          statusText: response.statusText,
          body: responseBody
        };
      }

      // 返回响应状态
      return JSON.stringify(this.lastResponse);
    } catch (error) {
      // 处理请求错误
      this.lastResponse = {
        error: error.message,
        status: 'error'
      };
      return JSON.stringify(this.lastResponse);
    }
  }

  getLastResponse() {
    if (this.lastResponse) {
      return JSON.stringify(this.lastResponse);
    }
    return JSON.stringify({status: 'no request made yet'});
  }
}

// 注册扩展
Scratch.extensions.register(new WebRequestExtension());
